package com.study.queue;

import java.util.Scanner;

public class AnnularArrayQueue {

    public static void main(String[] args) {
        Boolean loop = true;
        AnnularQueue queue = new AnnularQueue(3);

        while (loop){
            System.out.println("g: getElement");
            System.out.println("a: addElement");
            System.out.println("s: showQueue");
            System.out.println("h: showHead");
            System.out.println("e: exitProgram");
            Scanner scanner = new Scanner(System.in);
            String key = scanner.next();

            switch (key){
                case "g":
                    try {
                        queue.getElement();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    break;
                case "a":
                    System.out.println("please input the element that you want added");
                    int element = scanner.nextInt();
                    try {
                        queue.addElement(element);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    break;
                case "s":
                    queue.showQueue();
                    break;
                case "h":
                    queue.showHead();
                    break;
                case "e":
                    loop =false;
                    System.out.println("program is exit success");
                    break;
            }
        }
    }

    }

    class AnnularQueue{

        int front = 0;

        int rear = 0;

        int[] arr;

        int maxSize;
        public AnnularQueue(int maxSize){
            this.maxSize = maxSize;
            arr = new int[this.maxSize];
        }

        public Boolean isNull(){
            return rear == front;
        }

        public  Boolean isFull(){
            //对头指针在队尾指针的下一个位子时队列满
            return (rear +1)%maxSize == front;
        }
        public void addElement(int element){
            if(isFull()){
                throw new RuntimeException("queue is full");
            }
            arr[rear] = element;
            rear = (rear+1)% maxSize;
        }
        public void getElement(){
            if (isNull()){
                throw  new RuntimeException("queue is null");
            }
            System.out.println(arr[front]);
            front = (front+1)% maxSize;
        }
        public void showHead(){
            System.out.println(arr[front]);
        }
        public void showQueue(){
            int index =front;
            for (int i = 0; i <(rear + maxSize - front)%maxSize ; i++) {
                System.out.println(arr[index]);
                index = (index+1)%maxSize;
            }
        }

    }

